import React from 'react'
import {withRouter} from 'react-router'
import BaseComponent from 'basecomponent'
import classNames from 'classnames'
import icons from 'icons'
import Button from "button"
import Dropzone from 'react-dropzone'
import './style.scss'
import {Form, Select, Checkbox} from 'antd'
const FormItem = Form.Item
import api from 'apis'
const Option = Select.Option
import appConfig from 'config'
import {USER_KEY} from 'auth'
import store from 'store'
import {bannerType} from 'utils/staticType'

class Banner extends BaseComponent {
  constructor() {
    super(...arguments)
    const location = this.props.location
    this.state = {
      isRevise: location.state ? location.state.revise : false,
      bannerData: {
        Id: location.query.Id?  parseInt(location.query.Id) : -1,
        Image: '',
        Type: location.query.type?  parseInt(location.query.type) : -1,
        Name: '',
        Refer: ''
      },
      bannerLogoImg: '',
      bannerLogoPreview: '',
    }
    store.set('currentBannerId', location.query.Id ? location.query.Id : -1)
  }

  componentDidMount() {
    const {bannerData} = this.state
    if(this.handleID()){
      // this.getbannerDetail(bannerData.Id)
      let data = this.props.location.state.bannerData
      if(data){
        this.props.form.setFieldsValue({
          Name: data.Name,
          Refer: data.Refer,
        })
        this.setState({bannerData: data})
      }
    }else {
      this.props.form.setFieldsValue({
        Name: bannerData.Name,
        Refer: bannerData.Refer,
      })
    }
  }

  getbannerDetail(id) {
    let bannerId = id ? id : store.get('currentBannerId')
    this.getbannerDetailRP && this.getbannerDetailRP.request.abort()
    this.getbannerDetailRP = api.banner.getbannerDetail(bannerId)
    this.registerRequest(this.getbannerDetailRP.request)
    this.getbannerDetailRP.promise
      .then((res) => {
        console.log(res.Data)
        res.Data && this.setState({bannerData: res.Data})
        res.Data && this.mapbannerData(res.Data)
      })
  }


  handleLogoFileSelect(files) {
    const {bannerData} = this.state
    let file = files[0]
    if (file) {
      this.uploadLogoRP && this.uploadLogoRP.request.abort()
      this.uploadLogoRP = api.file.uploadFile(file)
      this.registerRequest(this.uploadLogoRP.request)
      this.uploadLogoRP.promise
        .then((res) => {
          this.setState({
            bannerLogoImg: res.Data || '', bannerData: Object.assign({},
              bannerData, {Image: res.Data || ''}),
            bannerLogoPreview: `${appConfig.apiHost}/File/?pid=${res.Data}&key=${store.get(USER_KEY)}`
          })
        })
        .catch((err) => {
          alert(err.msg)
        })
    }
  }

  handleSubmit(e) {
    e.preventDefault()
    const{bannerData} = this.state
    this.props.form.validateFields((err, values) => {
      if (!err) {
        bannerData.Name = values.Name
        bannerData.Refer = values.SubName
        if (this.handleID()){
          this.revisebannerRP && this.revisebannerRP.request.abort();
          this.revisebannerRP = api.banner.resiveBanner(bannerData.Id, bannerData);
          this.registerRequest(this.revisebannerRP.request);
          this.revisebannerRP.promise
            .then((res) => {
              res.Data && this.setState({bannerData: res.Data});
              alert('修改成功')
            })
            .catch((err) => {
              alert(err.msg)
            })
        } else {
          if(!(bannerData.Type === -1 || typeof bannerData.Type === 'undefined')){
            if(bannerData.Id) delete bannerData.Id
            this.addbannerRP && this.addbannerRP.request.abort();
            this.addbannerRP = api.banner.addBanner(bannerData);
            this.registerRequest(this.addbannerRP.request);
            this.addbannerRP.promise
              .then((res) => {
                res.Data && this.setState({bannerData: res.Data});
                alert('添加成功')
              })
              .catch((err) => {
                alert(err.msg)
              })
          }
          else{
            alert('添加banner出错')
          }
        }
      }
    })
  }
  handleID () {
    const {bannerData} = this.state
    return !(bannerData.Id === -1 || typeof bannerData.Id === 'undefined')
  }

  getLogoImgDiv() {
    const {bannerLogoImg, bannerLogoPreview} = this.state
    console.log('getLogoImgDiv')
    if (bannerLogoPreview.length > 0) {
      return <img className={'preview-img'} src={bannerLogoPreview}/>
    } else {
      if (bannerLogoImg.length > 0) {
        return <img className={'preview-img'}
                    src={`${appConfig.apiHost}/File/?pid=${bannerLogoImg}&key=${store.get(USER_KEY)}`}/>
      } else {
        return <div className={'default-wrapper'}>
          <img className={'image-default'} src={icons.uploadImg}/>
          <span>点击添加LOGO</span>
        </div>
      }
    }
  }

  render() {
    const {wrapperName, buttonWrapperName, clickBack, children} = this.props
    const {getFieldDecorator, getFieldsError, getFieldError, isFieldTouched} = this.props.form
    const {bannerData} = this.state
    return (
      children ? <div>{children}</div> :
        <div className={'sem-main-content'}>
          <div className={classNames('company-wrapper', wrapperName)}>
            <div className={classNames('button-wrapper', buttonWrapperName)}>
              <Button className={'back-button'} onClick={() => {
                  this.props.router.goBack()
              }}>{Button.AddOn({
                src: icons.backIcon, style: {
                  width: '1rem',
                  height: '1rem',
                  display: 'block',
                  backgroundRepeat: 'no-repeat',
                }
              })}</Button>
              <div className={'add-name'}>
                添加banner
              </div>
            </div>
            <Form onSubmit={this.handleSubmit.bind(this)} hideRequiredMark={true}>

              <div className={'body-top'} style={{height:'auto', padding:'2rem'}}>
                <Dropzone className={'image-drop-zone'}
                          onDrop={this.handleLogoFileSelect.bind(this)}
                          accept={'image/*'}
                          multiple={false}>
                  {this.getLogoImgDiv()}
                </Dropzone>
                <div className={'body-top-middle'} style={{display: 'flex'}}>
                  <div className={'option-wrapper'} style={{margin: 'auto'}}>
                    <div className={'option-title'}>名称</div>
                    <FormItem>
                      {getFieldDecorator('Name', {initialValue: bannerData.Name})(
                        <input className={'option-input'}
                               type={'text'}/>
                      )}
                    </FormItem>
                  </div>
                </div>
                <div className={'body-top-end'} style={{height: 'auto'}}>
                  <div className={'option-wrapper'}>
                    <div className={'option-title'}>链接</div>
                    <FormItem>{
                      getFieldDecorator('Refer')(
                        <input className={'option-input'}
                               type={'text'}/>
                      )
                    }</FormItem>
                  </div>
                </div>
              </div>
              <Button className={'title-btn-save'} buttonType={'submit'}  onClick={() => {
              }}>保存</Button>
            </Form>
          </div>
        </div>
    )
  }
}

module.exports = Form.create()(withRouter(Banner))
